<template>

  <el-scrollbar max-height="400px">
    <div style="height:65px" v-for="item in GroupAddMessageVo" :key="item.id" class="scrollbar-demo-item">
      <div>
        <span class="title">{{item.name}}</span>
        <el-avatar style="margin-left: 5px" shape="square" :src="url+item.userAvatar"/>
      </div>

      <div v-if="item.groupMaster == userInfo().id" style="width: 100px;font-size: 12px" >申请加入群聊</div>
      <div v-else style="width: 100px;font-size: 12px">邀请加入群聊</div>

      <div>
        <span class="title">{{item.groupName}}</span>
        <el-avatar style="margin-left: 5px" shape="square" :src="url+item.groupAvatar"/>
      </div>

      <div style="margin-right: 5px">
        <el-icon @click="agreeGroup(item)" style="color:#1aff00"><Select /></el-icon>
        <el-icon @click="refusalGroup(item)" style="color: red"><CloseBold /></el-icon>
      </div>
    </div>
  </el-scrollbar>

    <div class="card-header">
     <span>我的群</span>
    </div>
    <el-divider />
    <el-scrollbar max-height="400px">
      <div v-for="item in myGroup" :key="item.groupId" class="scrollbar-demo-item">
        <el-avatar shape="square" :src="url+item.avatar"/>
        <div class="text">{{ item.name }}</div>
        <a style="margin: 2px" v-if="item.children == null " @click="toInfo(item)"> <el-icon><Avatar /></el-icon> </a>
        <a style="margin: 2px"  v-if="item.children == null" @click="append(item)"> <el-icon><ChatLineSquare /></el-icon> </a>
        <a style="margin: 2px" v-if="item.label !== '默认分组'" @click="remove(item)"> <el-icon><DeleteFilled /></el-icon> </a>
      </div>
    </el-scrollbar>

    <div class="card-header">
      <span>我加入的群</span>
    </div>
    <el-divider />
    <el-scrollbar max-height="400px">
      <div v-for="item in otherGroup" :key="item.groupId" class="scrollbar-demo-item">
        <el-avatar shape="square" :src="url+item.avatar"/>
        <div class="text">{{ item.name }}</div>
        <a style="margin: 2px" v-if="item.children == null " @click="toInfo(item)"> <el-icon><Avatar /></el-icon> </a>
        <a style="margin: 2px"  v-if="item.children == null" @click="append(item)"> <el-icon><ChatLineSquare /></el-icon> </a>
        <a style="margin: 2px" v-if="item.label !== '默认分组'" @click="remove(item)"> <el-icon><DeleteFilled /></el-icon> </a>
      </div>
    </el-scrollbar>
    <el-row class="mb-4">
      <el-button type="primary" @click="CreateGroupShow = true">创建群聊</el-button>
      <el-button style="margin-left: auto" type="success" @click="GroupShow = true">加入群聊</el-button>
    </el-row>

  <el-dialog v-model="GroupShow" title="加入群聊">
    <el-form>
        <el-form-item label="群号" :label-width="formLabelWidth">
          <el-input v-model="intoGroup.groupNumber" autocomplete="off" />
        </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="quitIntoGroup">返回</el-button>
        <el-button type="primary" @click="addIntoGroup">
          提交
        </el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog v-model="CreateGroupShow" title="创建群聊">
    <el-form>
      <el-form-item label="群号" :label-width="formLabelWidth">
        <el-input v-model="createGroupRo.groupNumber" autocomplete="off" />
      </el-form-item >

      <el-form-item label="群名" :label-width="formLabelWidth">
        <el-input v-model="createGroupRo.name" autocomplete="off" />
      </el-form-item >

      <el-form-item label="头像" :label-width="formLabelWidth">
      <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :on-change="uploadFile"
          :auto-upload="false"
          ref="uploadRef"
      >
        <img v-if="createGroupRo.avatar" :src="url+createGroupRo.avatar" class="avatar"/>
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
      </el-form-item>

      <el-form-item label="邀请好友" :label-width="formLabelWidth">

        <el-tree-select
            v-model="value"
            :data="data"
            multiple
            :render-after-expand="false"
            show-checkbox
            @click="get"
        />

      </el-form-item >

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="quitCreateGroupShow">取消</el-button>
        <el-button type="primary" @click="submit">
          提交
        </el-button>
      </span>
    </template>
  </el-dialog>

</template>

<script lang="ts" setup>
import {onMounted, Ref, ref} from "vue";
import {
  addGroupUser,
  agree,
  createGroup, exitGroup,
  getGroup,
  getGroupAddMessage,
  intoGroupService,
  refusal
} from "../../service/GroupApi";
import {confirm, error, notifyMessage, success, websocketNotify} from "../../utils/messageUtil";
import {FileType, userInfo} from "../../utils/constant";
import {UploadFile} from "element-plus";
import {upload} from "../../service/FileApi";
import {getUserAccount, setAvatar} from "../../service/AccountApi";
import {getFriendGroup, getFriendShowVo} from "../../service/TieApi";
import {Tree} from "element-plus/lib/components/tree-v2/src/types";
import router from "../../router";
import {createSession} from "../../service/ChatApi";
import {callbacks, MessageDto, SessionType} from "../../utils/webSocket";
const url = ref(import.meta.env.VITE_APP_BASE_API + "/common/file/loadFileId?fileId=")

const formLabelWidth = '300px'
const myGroup: Ref<any[]> = ref([])
const otherGroup:Ref<any[]>  = ref([])
const GroupShow = ref(false)
const CreateGroupShow = ref(false)
const GroupAddMessageVo:Ref<any[]> = ref([])
const value = ref()
const data = ref<Tree[]>([]);

const emit = defineEmits(['clickChild'])

const clickChild=(session:any)=> {
  //传递给父组件
  emit('clickChild', session)
}

const remove = (data:any) => {
  if(data.groupMaster == userInfo().id){
    confirm("解散群聊","是否要解散群聊", ()=>{
      exit(data.groupId)
    })
  }else{
    confirm("退出群聊","是否要退出群聊", ()=>{
      exit(data.groupId)
    })
  }
}

const exit = (id: string)=>{
  exitGroup({
    groupId: id
  }).then((d)=>{
    if(d.data.code == 200){
      success("退出成功")
      getDate();
    }
  }).catch(()=>{
    error("网络错误")
  })
}

const append = (data: any) => {
  createSession({
    acceptId: data.groupId,
    sessionType: SessionType.GROUP
  }).then(d=>{
    if(d.data.code == "200") {
      clickChild(d.data.date);
      router.push({
        name: 'chat',
        query: d.data.date
      })
    }else{
      error(d.data.message)
    }
  }).catch(()=>{
    error("网络错误")
  })
}

const toInfo = (data:any) => {
  router.push({
    name:'groupInfo',
    query:{
      groupId: data.groupId,
    }
  })
}

const createGroupRo = ref({
  groupNumber:'',
  name:'',
  avatar:''
})

const intoGroup = ref({
  groupNumber:''
})

const quitCreateGroupShow = ()=>{
  console.log(value.value)
  value.value = null;
  CreateGroupShow.value = false;
  createGroupRo.value.groupNumber = '';
  createGroupRo.value.name = '';
  createGroupRo.value.avatar = '';
}

const submit = ()=>{
  if(createGroupRo.value.name ==''){
    error("请输入群名")
    return;
  }

  if(createGroupRo.value.groupNumber ==''){
    error("请输入群号")
    return;
  }

  if(createGroupRo.value.avatar == ''){
    error("请上传头像")
    return
  }

  createGroup(createGroupRo.value).then(d=>{
    if(d.data.code == 200){
      success("创建成功")
      getDate()
      addGroupUser({
        groupId: d.data.date,
        userIds: value.value
      })
    }else{
      error(d.data.message)
    }
  })
}

const quitIntoGroup = ()=>{
  intoGroup.value.groupNumber =''
  GroupShow.value = false
}

const addIntoGroup = ()=>{
  if(intoGroup.value.groupNumber==''){
    error("请输入群号")
    return;
  }
  intoGroupService({
    groupNumber: intoGroup.value.groupNumber
  }).then(d=>{
    if(d.data.code==200){
      success("请求成功")
      GroupShow.value=false;
    }else{
      error(d.data.message)
    }
    intoGroup.value.groupNumber=''
  }).catch(()=>{
    error("请求错误")
  })
}

onMounted(()=>{
  getDate();
  getAddMessage();

  callbacks.requestGroup = (messageDto:MessageDto)=>{
    getAddMessage()
    notifyMessage(`${messageDto.sendUserSocketDto.name}申请加入群聊`)
  }

  callbacks.inviteGroup = (messageDto:MessageDto)=>{
    getAddMessage()
    getDate()
    notifyMessage(`${messageDto.sendUserSocketDto.name}邀请您加入群聊`)
  }
})

const getAddMessage= ()=> {
  getGroupAddMessage().then(d=>{
    if(d.data.code == 200){
      GroupAddMessageVo.value = d.data.date;
    }else{
      error(d.data.message)
    }
  }).catch(d=>{
    error("网络错误")
  })
}

const getDate = ()=>{
  myGroup.value = [];
  otherGroup.value = [];
  getGroup().then(d=>{
    if(d.data.code == 200){
      d.data.date.forEach((item:any)=>{
        console.log(item)
        if(item.groupMaster===userInfo().id){
          myGroup.value.push(item)
        }else{
          otherGroup.value.push(item)
        }
      })
    }else{
      error(d.data.message)
    }
  }).catch(d=>{
    error("网络错误")
  })
}

const fileRo: any = {
  multipartFiles: [],
  fileType: FileType.USER_AVATAR
}

const uploadFile = (uploadFile: UploadFile) => {
  if(uploadFile.raw?.type == "image/jpeg" || uploadFile.raw?.type == "image/png"){
    if (uploadFile.raw.size / 1024 / 1024 > 2) {
      error('头像文件不能大于 2MB!')
      return false
    }
    fileRo.multipartFiles.push(uploadFile.raw);
    upload(fileRo).then(d => {
      if (d.data.code != '200') {
        error(d.data.message)
      }else{
        createGroupRo.value.avatar=d.data.date.fileIds[0]
      }
    }).catch(e => {
      error("网络异常")
    })
  }else{
    error("文件类型错误 只可以上传jpg和png图片")
  }
}

const get = ()=>{
  getFriendShowVo().then(d=>{
    if(d.data.code==200){
      data.value = d.data.date;
    }else{
      error(d.data.message)
    }
  }).catch(()=>{
    error("网络异常")
  })
}

const agreeGroup = (data:any)=>{
  agree({
    id:data.id
  }).then(d=>{
    if(d.data.code==200){
      getAddMessage()
      getDate()
    }else{
      error(d.data.message)
    }
  }).catch(()=>{
    error("网络异常")
  })
}

const refusalGroup = (data:any)=>{
  refusal({
    id:data.id
  }).then(d=>{
    if(d.data.code==200){
      getAddMessage()
    }else{
      error(d.data.message)
    }
  }).catch(()=>{
    error("网络异常")
  })
}

</script>

<style scoped>
.scrollbar-demo-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  margin: 10px;
  text-align: center;
  border-radius: 4px;
  background: #e0e0e0;
  color: black;
}

.card-header{
  margin: 10px;
}

.text {
  width: 120px;
}

.title {
  margin-bottom: 10px;
  font-size: 10px;
  color: #858585;
  background: #e0e0e0;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-input {
  width: 600px;
}

.el-button--text {
  margin-right: 15px;
}
.el-select {
  width: 300px;
}
.el-input {
  width: 300px;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>